import { showMsg, getAppList, updateApp } from '../../vuex/action'
import { modal } from 'vue-strap'
export default {
  name: 'UpdateApp',
  components: {
    'vue-modal': modal
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xGetAppList: getAppList,
      xUpdateApp: updateApp
    }
  },
  data() {
    return {
      checkIos: false,
      checkAndroid: false,
      iosData: {},
      androidData: {}
    }
  },
  ready() {
    this.getList()
  },
  methods: {
    getList() {
      this.xGetAppList()
        .then((data) => {
          for (var value of data.list) {
            if (value.platform === 0) {
              this.checkIos = true
              this.iosData = value
            } else if (value.platform === 1) {
              this.checkAndroid = true
              this.androidData = value
            }
          }
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    },
    submitUpdate() {
      var tips = this.checkData()
      if (tips !== 'ok') {
        return this.xShowMsg({
          type: 'danger',
          content: tips
        })
      }
      var params = this.getParams()
      this.xUpdateApp(params)
        .then((res) => {
          this.xShowMsg({
            type: 'info',
            content: '更新成功'
          })
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    },
    getParams() {
      let platform = []
      let version = []
      let description = []
      if (this.checkIos) {
        platform.push('0')
        version.push(this.iosData.version)
        description.push(this.iosData.description)
      }
      if (this.checkAndroid) {
        platform.push('1')
        version.push(this.androidData.version)
        description.push(this.androidData.description)
      }
      return {
        platforms: platform.join(),
        versions: version.join(),
        descriptions: description.join()
      }
    },
    checkData() {
      if (!this.checkIos && !this.checkAndroid) {
        return '至少选择一个平台'
      }
      if (this.checkIos) {
        var result = this.validation(this.iosData)
        if (result === 'ok') {
          return this.validation(this.androidData)
        } else {
          return result
        }
      }
      if (this.checkAndroid) {
        return this.validation(this.androidData)
      }
    },
    validation(d) {
      if ((d.version + '').length === 0) {
        return '版本不能为空'
      }
      var reg = /^\d+(\.\d+){2}$/
      if (!reg.test(d.version)) {
        return '版本号格式不正确'
      }
      if (d.description.length === 0) {
        return '描述不能为空'
      }
      return 'ok'
    }
  }
}
